from templates import template_render
from urllib2 import HTTPError
import web
import simplejson
from printer import  _Printer
from gcp import GoogleCloudPrint
from session import need_auth, AuthBase

class MyPrinters(AuthBase):
    @need_auth
    def GET(self):
        self.setSessionCookie()
        session = self.getSession()
        api = GoogleCloudPrint(user=session.user)
        try:
            printers = [] # output                
            str_rsp = api.search_printers()
            json_data = simplejson.loads(str_rsp)
            if (json_data['success']):
                for p in json_data['printers']:
                    out = {}
                    out['id'] = p['id']
                    out['name'] = p['name']
                    eprint = _Printer.Get(out['id'], session.user)
                    out['eprint_enabled'] = eprint and eprint.eprint_enabled or False
                    out['publish_addr'] = eprint and eprint.publish_addr or ''
                    out['verify_sender_address'] = eprint and eprint.verify_sender_address or False
                    out['allowed_sender_addresses'] = eprint and eprint.allowed_sender_addresses or [] 
                    
                    printers.append(out)
                printers = sorted(printers, key=lambda k: k['id'])
            return template_render.myprinters(user=session and session.user or None, printers=printers)
        except HTTPError: # token expiration? or others, re-auth again
            raise web.seeother('/signin')
